package cn.com.infohold.smartcity.jpush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.com.infohold.smartcity.api.GsonUtils;
import cn.com.infohold.smartcity.api.SDK;
import cn.com.infohold.smartcity.api.bean.Message;
import cn.com.infohold.smartcity.data.XmlConfig;
import cn.com.infohold.smartcity.data.XmlData;
import cn.com.infohold.smartcity.utils.PushUtils;
import cn.jpush.android.api.JPushInterface;
import library.utils.Logger;
import library.utils.Utils;


/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class JpushReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null)
            return;

        final Bundle bundle = intent.getExtras();
        final String action = intent.getAction();
        final String event = getActionName(action);
        final String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
        final String msgId = bundle.getString(JPushInterface.EXTRA_MSG_ID);

        try {
            JSONObject json = new JSONObject();
            json.put("Provider", "Jpush");
            json.put("Action", action);
            json.put("Event", event);
            json.put("MsgId", msgId);
            json.put("Extra", extra != null ? new JSONObject(extra) : null);
            Logger.json(json.toString());
        } catch (Exception e) {
            Logger.debug(e);
        }

        if (TextUtils.isEmpty(action))
            return;
        if (TextUtils.isEmpty(event))
            return;

        if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Utils.startAPP(context);
            return;
        }

        try {
            if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(action)) {
                handleState(context, msgId, JPushInterface.getConnectionState(context));
            } else if (!TextUtils.isEmpty(extra))
                handleMsg(context, msgId, extra);
        } catch (Exception e) {
            Logger.debug(e);
        }
    }

    private void handleState(Context context, String msgId, boolean conn) {
        if (conn && !isAllowPush()) {
            JPush.unbind(context);
        }
    }

    public boolean isAllowPush() {
        boolean canPush = XmlConfig.getInstance().isAutoLogin()
                && !TextUtils.isEmpty(XmlData.getInstance().getUsername())
                && !TextUtils.isEmpty(XmlData.getInstance().getPassword());
        return canPush;
    }

    private void handleMsg(Context context, String msgId, String extra) {
        JpushExtra jpushExtra = GsonUtils.fromJson(extra, JpushExtra.class);
        if (jpushExtra == null || !isAllowPush())
            return;
        switch (jpushExtra.getType()) {
            case 4:
                String news = jpushExtra.getMessage();
                Message message = SDK.getGson().fromJson(news, Message.class);
                if (message != null && message.getId() != null) {
                    PushUtils.getInstance(context).pushMessage(message);
                    EventBus.getDefault().post(message);
                }
                break;
            case 5:
//                Session session = XmlData.getInstance().getSession();
//                long loginTime = session != null ? session.getTime() : 0;
//                if (jpushExtra.getTime() > loginTime) {
//                    JPush.unbind(context);
//                    EventBus.getDefault().post(jpushExtra);
//                }
                break;
        }
    }

    private String getActionName(String type) {
        Map<String, String> types = new HashMap<String, String>();
        types.put(JPushInterface.ACTION_REGISTRATION_ID, "接收Registration");
        types.put(JPushInterface.ACTION_MESSAGE_RECEIVED, "接收到推送下来的自定义消息");
        types.put(JPushInterface.ACTION_NOTIFICATION_RECEIVED, "接收到推送下来的通知");
        types.put(JPushInterface.ACTION_NOTIFICATION_OPENED, "用户点击打开了通知");
        types.put(JPushInterface.ACTION_RICHPUSH_CALLBACK, "用户收到到RICH PUSH CALLBACK");
        types.put(JPushInterface.ACTION_CONNECTION_CHANGE, "connected state change");
        return types.get(type);
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\n``:" + key + ", value:" + bundle.getBoolean(key));
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }
}
